package com.h3bpm.starcharge.service.impl.eseal;

import api.APIController;
import com.h3bpm.starcharge.common.bean.Bestsign_file;
import com.h3bpm.starcharge.service.eseal.ESealService;
import com.h3bpm.starcharge.support.core.ContractsType;
import com.h3bpm.starcharge.support.eseal.ContractsFactory;
import com.h3bpm.starcharge.support.eseal.ESealHandler;
import com.h3bpm.starcharge.support.eseal.NoStandard;
import com.h3bpm.starcharge.support.eseal.Signature;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @ClassName ESealServiceImpl
 * @Desciption 电子章
 * @Author lvyz
 * @Date 2019/6/10 20:35
 **/
@Service
public class ESealServiceImpl implements ESealService {


	@Override
	@Transactional
	public String synContract(String instanceId, String contractCode) {

		// 获取合同类型
		ContractsType contractsType = ContractsType.getContractsType(contractCode);

		// 根据合同类型获取处理器
		ESealHandler handler = ContractsFactory.create(contractsType);

		// 同步合同到上上签
		String contractId = handler.synContract(instanceId);

		// 更新合同编号
		this.updateContractId(instanceId, contractId);

		return contractId;
	}

	@Override
	@Transactional
	public String upLoadContract(String instanceId) {

		ESealHandler handler = new NoStandard();

		String contractId = handler.uploadContract(instanceId);

		// 更新合同编号
		this.updateContractId(instanceId, contractId);

		return instanceId;
	}

	@Override
	public void signature(String contractId, String sealName, String companyName) {

		ESealHandler handler = new Signature();


		if(StringUtils.isBlank(sealName) || StringUtils.isBlank(companyName)){

			// 加盖本公司章
			handler.signature(contractId);
		}else{

			// 加盖选择的企业的章
			handler.signature(contractId, sealName, companyName);
		}

	}

	/**
	 * 更新合同编号
	 *
	 * @param instanceId
	 * @param contractId
	 */
	@Transactional
	private void updateContractId(String instanceId, String contractId) {

		Bestsign_file bestSignFile = APIController.queryFile(instanceId, "previewAfter");

		APIController apiController = new APIController();

		if (null == bestSignFile) {
			apiController.previewAfter(instanceId, contractId);
			return;
		}

		// 当instanceId存在合同但是两次contractId又不一致，说明合同有更新。需要先删除再重新插入
		if (!bestSignFile.getContractId().equals(contractId)) {
			APIController.deleteFile(instanceId);
			apiController.previewAfter(instanceId, contractId);
		}
	}
}
